package com.fjh.service;
import com.fjh.DatabaseConnector;
import com.fjh.pojo.Product;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class ProductService {
    // 添加商品到数据库
    public void add(Product product) {
        try (Connection connection = DatabaseConnector.connect()) {
            String sql = "INSERT INTO products (id, name, stock) VALUES (?, ?, ?)";
            try (PreparedStatement statement = connection.prepareStatement(sql)) {
                statement.setString(1, product.getId());
                statement.setString(2, product.getName());
                statement.setInt(3, product.getStock());
                statement.executeUpdate();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 根据ID查找商品
    public Product findById(String id) {
        try (Connection connection = DatabaseConnector.connect()) {
            String sql = "SELECT * FROM products WHERE id = ?";
            try (PreparedStatement statement = connection.prepareStatement(sql)) {
                statement.setString(1, id);
                try (ResultSet resultSet = statement.executeQuery()) {
                    if (resultSet.next()) {
                        String name = resultSet.getString("name");
                        int stock = resultSet.getInt("stock");
                        return new Product(id, name, stock);
                    }
                }
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    // 更新商品信息
    public void update(Product product) {
        try (Connection connection = DatabaseConnector.connect()) {
            String sql = "UPDATE products SET name = ?, stock = ? WHERE id = ?";
            try (PreparedStatement statement = connection.prepareStatement(sql)) {
                statement.setString(1, product.getName());
                statement.setInt(2, product.getStock());
                statement.setString(3, product.getId());
                statement.executeUpdate();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

    // 从数据库中移除商品
    public void remove(String id) {
        try (Connection connection = DatabaseConnector.connect()) {
            String sql = "DELETE FROM products WHERE id = ?";
            try (PreparedStatement statement = connection.prepareStatement(sql)) {
                statement.setString(1, id);
                statement.executeUpdate();
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}


